package io.bdmc.modules.job.task;

import java.time.LocalDateTime;
import java.util.List;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import io.bdmc.common.http.ZxyDeviceDetail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import io.bdmc.common.http.ZxyDeviceData;
import io.bdmc.common.http.ZxyHttpUtil;
import io.bdmc.modules.bss.entity.SmkDevice;
import io.bdmc.modules.bss.service.ISmkDeviceService;
import org.springframework.util.StringUtils;

/**
 * 定时获取中消云数据的任务
 *
 * @author huang lu
 * @email hlkyo@qq.com
 * @date 2016年11月30日 下午1:34:24
 */
@Component("zxyAutoDataTask")
public class ZxyAutoDataTask {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    ISmkDeviceService _devSvs;

    @Resource
    ZxyHttpUtil _zxyUtil;

    public void autoData(String params) {
        logger.info("自动获取中消云数据，正在被执行......");
        QueryWrapper<SmkDevice> w1 = new QueryWrapper<>();
        w1.eq("dev_manufactory", "中消云");
        List<SmkDevice> devList = _devSvs.list(w1);
        LocalDateTime now = LocalDateTime.now();
        for (SmkDevice dev : devList) {
            if(StringUtils.isEmpty(dev.getDevKey())||dev.getDevKey().equals(dev.getImei())){
                String data = _zxyUtil.getDeviceList(dev.getImei());
                List<ZxyDeviceDetail> jsarr= JSONArray.parseArray(data, ZxyDeviceDetail.class);
                dev.setDevKey(jsarr.get(0).getDeviceId());
            }
            String data = _zxyUtil.getDeviceAttribute(dev.getDevKey());
            ZxyDeviceData d = JSON.parseObject(data,ZxyDeviceData.class) ;
            dev.setBatteryPower(d.getVoltage());
            dev.setSignalSnr(d.getSignalSnr());
            dev.setSignalEcl(d.getSignalEcl());
            dev.setSignalStrength(d.getSignalStrength());
            dev.setIccid(d.getIccid());
            dev.setSmokeScope(d.getConcentration());
            dev.setUpdateDate(now);
        }
        boolean b = _devSvs.updateBatchById(devList);
        logger.info("自动获取中消云数据执行完成，更新结果："+b);
    }
}